import { login } from '@/api/user'
import { getToken, setToken, removeToken, getUserInfo, setUserInfo } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: getUserInfo(),
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
}

const actions = {
  login({ commit, state }, userInfo) {
    console.log('userInfo',userInfo)
    const { username, password} = userInfo
    return new Promise((resolve, reject) => {
      console.log('login', username, password)
      if (username === 'admin' && password === 'admin') {
        let data = {
            token: 'admin-token',
            phone: 'admin',
            password: 'admin',
        }
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        setUserInfo({
          ...data
        })
        commit('SET_USERINFO', {
          ...data
        })
        resolve()
      } else {
        reject('用户名或密码错误')
      }
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

